import JSEncrypt from 'jsencrypt';
import crypto from 'crypto-js';
let pubKey = `MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCS2Hn5Gi6Fiz4R8z2StMvsoF4y
HKsmGvjInTOrZ1r9ScrFIvGjPuPi3OT2swvq3smTN4avvrTt/EeOZFZUD0qT2URi
b5kOIrSDbdu6YGZ+L2lKyaVd/WWsuY39kUF7QHhPQX2qsCOH0Q9g5yja9qH4OR5I
x4qKjZlRIxJfTz9dxQIDAQAB`;

// 获取16位十六进制随机数
function getRamNumber() {
  var result = '';
  for (var i = 0; i < 16; i++) {
    result += Math.floor(Math.random() * 16).toString(16); //获取0-15并通过toString转16进制
  }

  //默认字母小写，手动转大写
  return result.toLowerCase(); //另toLowerCase()转小写
}
class RSA {
  constructor(obj) {
    // 十六位十六进制数作为密钥
    this.key = obj && obj.key ? obj.key : getRamNumber();
    this.iv = obj && obj.iv ? obj.iv : getRamNumber();
    this.SECRET_KEY = crypto.enc.Utf8.parse(this.key);
    // 十六位十六进制数作为密钥偏移量
    this.SECRET_IV = crypto.enc.Utf8.parse(this.iv);
  }

  /**
   * AES加密
   * @param {string} data 需要加密的数据
   * @returns {string} base64
   */
  encrypt(data, employee) {
    if (typeof data === 'object') {
      try {
        data = JSON.stringify(data);
      } catch (error) {
        console.log('encrypt error:', error);
      }
    }
    const dataHex = crypto.enc.Utf8.parse(data);
    const encrypted = crypto.AES.encrypt(dataHex, this.SECRET_KEY, {
      iv: this.SECRET_IV,
      mode: crypto.mode.CBC,
      padding: crypto.pad.Pkcs7
    });
    let encryptedHexStr = crypto.enc.Base64.stringify(encrypted.ciphertext); // 转base64
    return encryptedHexStr;
  }
  /**
   * AES解密
   * @param {string} str 需要解密的数据
   * @returns {string} base64
   */
  decrypt(str) {
    //  base64Str = crypto.enc.Base64.stringify(wordArray);
    var decrypted = crypto.AES.decrypt(str, this.SECRET_KEY, {
      iv: this.SECRET_IV,
      mode: crypto.mode.CBC,
      padding: crypto.pad.Pkcs7
    });
    let decryptedStr = decrypted.toString(crypto.enc.Utf8);
    return decryptedStr;
  }
  /**
   * rsa公钥加密
   * @param {string} str 需要加密的数据
   * @returns {string} base64
   */
  RSAencrypt(str) {
    let encrypt = new JSEncrypt();
    encrypt.setPublicKey('-----BEGIN PUBLIC KEY-----' + pubKey + '-----END PUBLIC KEY-----');
    let encrypted = encrypt.encrypt(str, 'base64');
    return encrypted;
  }
}

export default RSA;
